package com.example.j202411.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.example.j202411.R;
import com.example.j202411.Model.CatalogEntity;
import com.example.j202411.views.Activity.BooksActivity;

import java.util.ArrayList;
import java.util.List;

public class CatalogAdapter extends RecyclerView.Adapter<CatalogAdapter.ViewHolder> {
    private static final String TAG = "CatalogAdapter";
    private List<CatalogEntity.ResultDTO> mlist;
    private Context context;

    public CatalogAdapter(List<CatalogEntity.ResultDTO> list, Context context) {
        this.mlist = new ArrayList<>(list);
        this.context = context;
        Log.d(TAG, "Constructor called with list size: " + mlist.size());
    }

    public void updateData(List<CatalogEntity.ResultDTO> list) {
        Log.d(TAG, "updateData called with list size: " + list.size());
        mlist.clear();
        mlist.addAll(list);
        Log.d(TAG, "mlist updated with size: " + mlist.size());
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.d(TAG, "onCreateViewHolder called");
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_catalog, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Log.d(TAG, "onBindViewHolder called for position: " + position);
        CatalogEntity.ResultDTO data = mlist.get(position);
        if (data != null) {
            Log.d(TAG, "Binding data: " + data.getCatalog());
            holder.name.setText(data.getCatalog());
            holder.itemView.setOnClickListener(v -> {
                Log.d(TAG, "Item clicked at position: " + position);
                Intent intent = new Intent(context, BooksActivity.class);

                intent.putExtra("catalog_id", data.getId()); // 假设 ResultDTO 有一个 getId 方法
                context.startActivity(intent);
                Log.d(TAG, "Intent started with data: " + data);
            });
        } else {
            Log.e(TAG, "Data is null at position: " + position);
        }
    }

    @Override
    public int getItemCount() {
        Log.d(TAG, "getItemCount called, returning: " + mlist.size());
        return mlist.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name01);
            Log.d(TAG, "ViewHolder created with name: " + name);
        }
    }
}